//
//  JBSNSShare.m
//  
//
//  Created by zhangyongbin on 7/14/15.
//
//

#import "JBSNSShare.h"
#import "UMSocial.h"
#import "UMSocialSinaSSOHandler.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"

#define JBSNSShareErrorDomain @"JBSNSShareErrorDomain"

@interface JBSNSShare () <UIActionSheetDelegate, UMSocialUIDelegate>

@property (nonatomic, strong) NSString *sharePlatformAppKey;
@property (nonatomic, strong) NSString *appWebSitURL;

@property (nonatomic, strong) NSString *shareTitle;
@property (nonatomic, strong) NSString *shareContent;
@property (nonatomic, strong) NSString *shareURL;
@property (nonatomic, strong) id shareImage;

@property (nonatomic, copy) JBSNSShareResultBlock snsShareResultBlock;

@end

@implementation JBSNSShare

- (id)init
{
    self = [super init];
    if (self) {
        
//        [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToSina, UMShareToQQ, UMShareToQzone, UMShareToWechatSession, UMShareToWechatTimeline]];
    }
    
    return self;
}

+ (JBSNSShare *)sharedSNSShare
{
    static JBSNSShare *staticSNSShare;
    static dispatch_once_t onceTokenForStaticSNSShare;
    dispatch_once(&onceTokenForStaticSNSShare, ^{
        if (staticSNSShare == nil) {
            staticSNSShare = [[JBSNSShare alloc] init];
        }
    });
    
    return staticSNSShare;
}

/**
 设置第三方SNS分享平台的AppKey
 @param appKey 第三方SNS分享平台appKey
 */
+ (void)setSNSSharePlatformAppKey:(NSString *)appKey
{
    JBSNSShare *snsShare = [self sharedSNSShare];
    snsShare.sharePlatformAppKey = appKey;
    
    //设置友盟社会化组件appkey
    [UMSocialData setAppKey:appKey];
}

/**
 设置App的网站的URL地址
 @param url App网站
 */
+ (void)setAppWebSitURL:(NSString *)url
{
    [self sharedSNSShare].appWebSitURL = url;
}

/**
 设置SNS平台的AppId、AppKey和SecretKey
 @param snsType SNS平台类型
 @param appId SNS平台上的appId，若没有则传入nil
 @param appKey SNS平台上的appKey或SecretKey，若没有则传入nil
 @param appSecret SNS平台的appSecret或secretKey，若没有则传入nil
 */
+ (void)setSNSAuthInfoWithSnsType:(JBSNSType)snsType appId:(NSString *)appId appKey:(NSString *)appKey appSecret:(NSString *)appSecret
{
    if (snsType == JBSNSTypeSinaWeibo) {
        // TO DO
    } else if (snsType == JBSNSTypeQQ) {
        [UMSocialQQHandler setQQWithAppId:appId appKey:appKey url:[self sharedSNSShare].appWebSitURL];
    } else if (snsType == JBSNSTypeWechat) {
        [UMSocialWechatHandler setWXAppId:appId appSecret:appSecret url:[self sharedSNSShare].appWebSitURL];
    }
}

/**
 打开新浪微博的SSO开关，设置新浪微博回调地址，这里必须要和你在新浪微博后台设置的回调地址一致
 @param redirectURL 新浪微博回调地址
 */
+ (void)openSinaWeiboSSOWithRedirectURL:(NSString *)redirectURL
{
    if (redirectURL) {
        [UMSocialSinaSSOHandler openNewSinaSSOWithRedirectURL:redirectURL];
    } else {
        [UMSocialSinaSSOHandler openNewSinaSSOWithRedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    }
}

/**
 处理app的URL方法
 @param url 传入的url
 @return true/false 处理结果
 */
+ (BOOL)handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
}

/**
 当应用从后台唤起时，应调用此方法，需要完成退出当前登录状态的功能
 */
+(void)applicationDidBecomeActive
{
    [UMSocialSnsService applicationDidBecomeActive];
}

/**
 弹出一个分享列表的类似UIActivityViewController控件
 
 @param controller 在该controller弹出分享列表的UIActionSheet
 @param appKey 友盟appKey
 @param shareText  分享编辑页面的内嵌文字
 @param shareImage 分享内嵌图片,用户可以在编辑页面删除
 @param completionBlock 发送完成执行的block对象
 */
+(void)presentSnsIconSheetView:(UIViewController *)controller
                         title:(NSString *)title
                       content:(NSString *)content
                         image:(id)image
                           url:(NSString *)url
                    completion:(JBSNSShareResultBlock)completionBlock
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self sharedSNSShare].shareTitle = title;
        [self sharedSNSShare].shareContent = content;
        [self sharedSNSShare].shareImage = image;
        [self sharedSNSShare].shareURL = url;
        
        [UMSocialSnsService presentSnsIconSheetView:controller
                                             appKey:[self sharedSNSShare].sharePlatformAppKey
                                          shareText:content
                                         shareImage:image
                                    shareToSnsNames:@[UMShareToSina, UMShareToQQ, UMShareToQzone, UMShareToWechatSession, UMShareToWechatTimeline]
                                           delegate:[self sharedSNSShare]];
    });
}

/**
 分享文本+图片到SNS平台
 @param snsType             分享类型
 @param title               分享内容标题
 @param content             分享的文字内容
 @param image               分享的图片
 @param url                 点击分享内容后的跳转链接
 @param controller          在该controller进行分享
 @param completion          发送完成执行的block对象
 */
+ (void)shareWithShareType:(JBSNSShareType)snsShareType Title:(NSString *)title Content:(NSString *)content image:(UIImage *)image url:(NSString *)url presentedController:(UIViewController *)controller completion:(JBSNSShareResultBlock)completionBlock
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self sharedSNSShare].shareTitle = title;
        [self sharedSNSShare].shareContent = content;
        [self sharedSNSShare].shareImage = image;
        [self sharedSNSShare].shareURL = url;
        [self sharedSNSShare].snsShareResultBlock = completionBlock;
        
        UMSocialDataService *socialDataService = [UMSocialDataService defaultDataService];
        
        [UMSocialData defaultData].title = [self sharedSNSShare].shareTitle;
        [UMSocialData defaultData].shareText = content;
        [UMSocialData defaultData].shareImage = [self sharedSNSShare].shareImage;
        
        NSString *snsType = UMShareToSina;
        switch (snsShareType) {
            case JBSNSShareTypeToSinaWeibo:
                snsType = UMShareToSina;
                [UMSocialData defaultData].shareText = [NSString stringWithFormat:@"%@ %@", [UMSocialData defaultData].shareText, url];
                break;
                
            case JBSNSShareTypeToMobileQQ:
                snsType = UMShareToQQ;
                [UMSocialData defaultData].extConfig.qqData.title = [self sharedSNSShare].shareTitle;
                [UMSocialData defaultData].extConfig.qqData.url = [self sharedSNSShare].shareURL;
                break;
                
            case JBSNSShareTypeToQzone:
                snsType = UMShareToQzone;
                [UMSocialData defaultData].extConfig.qzoneData.title = [self sharedSNSShare].shareTitle;
                [UMSocialData defaultData].extConfig.qzoneData.url = [self sharedSNSShare].shareURL;
                break;
                
            case JBSNSShareTypeToWechatSession:
                snsType = UMShareToWechatSession;
                [UMSocialData defaultData].extConfig.wechatSessionData.url = [self sharedSNSShare].shareURL;
                [UMSocialData defaultData].extConfig.wechatSessionData.title = [self sharedSNSShare].shareTitle;
                [UMSocialData defaultData].extConfig.wechatSessionData.shareText = [self sharedSNSShare].shareContent;
                break;
                
            case JBSNSShareTypeToWechatTimeline:
                snsType = UMShareToWechatTimeline;
                [UMSocialData defaultData].extConfig.wechatTimelineData.url = [self sharedSNSShare].shareURL;
                [UMSocialData defaultData].extConfig.wechatTimelineData.title = [NSString stringWithFormat:@"%@ %@", [self sharedSNSShare].shareTitle, [self sharedSNSShare].shareContent];
                break;
                
            default:
                break;
        }
        
        [socialDataService postSNSWithTypes:@[snsType] content:[UMSocialData defaultData].shareText image:[self sharedSNSShare].shareImage location:nil urlResource:nil presentedController:controller completion:^(UMSocialResponseEntity * response){
            if (completionBlock) {
                if (response.responseCode == UMSResponseCodeSuccess) {
                    completionBlock(nil);
                } else if(response.responseCode != UMSResponseCodeCancel) {
                    completionBlock(response.error);
                }
            }
        }];
    });
}



#pragma mark -
#pragma mark - UMSocialUIDelegate

-(void)didSelectSocialPlatform:(NSString *)platformName withSocialData:(UMSocialData *)socialData
{
    UMSocialUrlResource *urlRes = [[UMSocialUrlResource alloc] initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:self.shareURL];
    
    socialData.title = self.shareTitle;
    socialData.urlResource = urlRes;
    
    if (platformName == UMShareToSina) {
        // TO DO
    } else if (platformName == UMShareToQQ) {
        socialData.extConfig.qqData.title = self.shareTitle;
        socialData.extConfig.qqData.url = self.shareURL;
        socialData.extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
    } else if (platformName == UMShareToQzone) {
        socialData.extConfig.qzoneData.title = self.shareTitle;
        socialData.extConfig.qzoneData.url = self.shareURL;
    } else if (platformName == UMShareToWechatSession) {
        socialData.extConfig.wechatSessionData.url = self.shareURL;
        socialData.extConfig.wechatSessionData.title = self.shareTitle;
        socialData.extConfig.wechatSessionData.shareText = self.shareContent;
        socialData.extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
    } else if (platformName == UMShareToWechatTimeline) {
        socialData.extConfig.wechatTimelineData.url = self.shareURL;
        socialData.extConfig.wechatTimelineData.title = [NSString stringWithFormat:@"%@ %@", self.shareTitle, self.shareContent];
        socialData.extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
    }
}

-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    if (self.snsShareResultBlock) {
        if (response.responseCode == UMSResponseCodeSuccess) {
            self.snsShareResultBlock(nil);
        } else if(response.responseCode != UMSResponseCodeCancel) {
            self.snsShareResultBlock(response.error);
        }
    }
}

@end
